<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use App\User;
use App\Supervisor;

class UserController extends Controller
{

    public function edit_password() {
        $error = "";
        $user = \Auth::user();
        return view('admin.resetuserpassword', compact("user", "error"));
    }

    public function store_password(Request $request) {
        $user = \Auth::user();
        $this->validate($request, [
            'username'=>'required|min:6'
        ]);

        $resetUser = User::where('username', $request->input("username"))->first();
        if ($resetUser == null) {
            $error = "没有该用户" . $request->input("username");
        } else {
            //$resetUser = User::find(304);
            $resetUser->update(["password" => bcrypt("123456")]);
            $error = "修改成功";
        }

        return view('admin.resetuserpassword', compact("user", "error"));
    }

    public function add_user_edit() {
        $user = \Auth::user();
        return view('admin.add_user', compact("user"));
    }

    public function add_user(Request $request) {

        $user = User::where('username', $request->input('username'))->first();
        if ($user == null) {
            $user = new User;
            $user->role = $request->input('role');
            $user->name = $request->input('name');
            $user->username = $request->input('username');
            $user->phone = $request->input('phone');
            $user->email = $request->input('email');
            $user->password = bcrypt("123456");
            $user->save();

        }
        $user = User::where('username', $request->input('username'))->first();
        $supervisor = Supervisor::where('user_id', $user->id)->first();
        if ($supervisor == null) {
            $supervisor = new Supervisor;
            $supervisor->user_id = $user->id;
            $supervisor->major = $request->input('major');
            $supervisor->job = $request->input('job');
            $supervisor->title = $request->input('title');
            $supervisor->quota = $request->input('quota');
            $supervisor->save();
        }
        return redirect()->back()->withInput()->withErrors('增加用户成功');
    }
}
